package jp.co.brilliantservice.app.sos;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.location.Location;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

public class CellLocationAsyncTask extends android.os.AsyncTask<String,Integer,Boolean> {
    private GsmCellLocation mGsmCellLocation = null;
    private int mCellId;
    private int mLac;
    private double[] mLocations = new double[2];
    private static final String GoogleCellID_URL = "http://www.google.com/glm/mmap";
    private Context mContext;
    private Location mLocation;

    
    private onPosteExecuteListener mOnPosteExecuteListener = null;

	private ProgressDialog mDialog;

	public CellLocationAsyncTask(Context context, boolean noDialog) {
	    mContext = context;
		if (!noDialog) {
			mDialog = new ProgressDialog(context);
		}
	}

	@Override
	protected void onPreExecute() {
		if (mDialog!=null) {
	        mDialog.setMessage("Now in progress...");
	        mDialog.setCancelable(true);
	        mDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					cancel(true);
				}
			});
	        mDialog.show();
		}
		super.onPreExecute();
	}

	@Override
	protected Boolean doInBackground(String... params) {
		boolean ret = false;
        final TelephonyManager telephonyManager = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
        if (mGsmCellLocation == null) {
            mGsmCellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
        }
        updateCelllocation();
		return ret;
	}

    private void updateCelllocation() {
        mCellId = mGsmCellLocation.getCid();
        mLac = mGsmCellLocation.getLac();
        if(mCellId==-1||mLac==-1){
                Log.d("CellID","Can't not get cellid and lac,use test data instead of");
                mCellId =20442;
                mLac =6015;
        }
        Log.e("Cell ID", ""+mCellId);
        Log.e("LAC", ""+mLac);

        try {
            getCurrentLocation_google_map_api(mLocations, mCellId, mLac);
            mLocation = new Location("manual");
            mLocation.setLatitude(mLocations[0]);
            mLocation.setLongitude(mLocations[1]);
            Log.e("celllocation", "lat="+mLocations[0]+" lng="+mLocations[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private boolean getCurrentLocation_google_map_api(double[] location,int cellID,int lac) throws Exception {
        boolean result = true;
        String urlString = GoogleCellID_URL;

        //---open a connection to Google Maps API---
        URL url;
        url = new URL(urlString);

        URLConnection conn = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection)conn;
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setConnectTimeout(10000);
        httpConn.connect();

        //---write some custom data to Google Maps API---
        OutputStream outputStream = httpConn.getOutputStream();
        WriteData(outputStream, cellID, lac);

        //---get the response---
        InputStream inputStream = httpConn.getInputStream();
        DataInputStream dataInputStream = new DataInputStream(inputStream);

        //---interpret the response obtained---
        Log.e("LocationUpdateService","short="+dataInputStream.readShort());
        Log.e("LocationUpdateService","byte="+dataInputStream.readByte());
        int code = dataInputStream.readInt();
        Log.e("LocationUpdateService","code="+code);
        if (code == 0) {
            double lat = (double) dataInputStream.readInt() / 1000000D;
            double lng = (double) dataInputStream.readInt() / 1000000D;
            dataInputStream.readInt();
            dataInputStream.readInt();
            dataInputStream.readUTF();
            dataInputStream.close();

            location[0] = lat;
            location[1]= lng;
        } else {
            result = false;
        }
        httpConn.disconnect();
        return result;
    }

    private void WriteData(OutputStream out, int cellID, int lac) throws IOException {
        DataOutputStream dataOutputStream = new DataOutputStream(out);
        dataOutputStream.writeShort(21);
        dataOutputStream.writeLong(0);
        dataOutputStream.writeUTF("ja");
        dataOutputStream.writeUTF("Android");
        dataOutputStream.writeUTF("1.0");
        dataOutputStream.writeUTF("Web");
        dataOutputStream.writeByte(27);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(3);
        dataOutputStream.writeUTF("");

        dataOutputStream.writeInt(cellID);
        dataOutputStream.writeInt(lac);

        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.flush();
        dataOutputStream.close();
    }
	
	
	@Override
	protected void onPostExecute(Boolean result) {
		if (mDialog!=null) {
			mDialog.dismiss();
		}
		if (mOnPosteExecuteListener != null) {
		    mOnPosteExecuteListener.onPosteExecute(mLocation);
		}
	}

	public void setOnPostedExecuteListener(onPosteExecuteListener listener) {
		mOnPosteExecuteListener = listener;
	}
	public interface onPosteExecuteListener {
		void onPosteExecute(Location location);
	}
}
